import axios from "axios";
import useUserStore from "@/stores/user";
import router from "@/router";
import { ElMessage } from "element-plus";

//创建axios实例
const instance = axios.create({
  baseURL: "http://127.0.0.1:80", //请求基地址
  timeout: 5000, //请求超时时间
});

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 有些接口不需要token,如注册，登录

    const userStore = useUserStore();
    if (config.url.startsWith("/my")) {
      config.headers.Authorization = `Bearer ${userStore.token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 成功响应
    return response;
  },
  (error) => {
    const userStore = useUserStore();
    // 失败响应   4xx 5xx
    // console.log(error);
    if (error.response.status === 401) {
      ElMessage.error(error.response.data.message);
      userStore.updateToken(null);
      router.push("/login");
    }

    return Promise.reject(error);
  }
);

export default instance;
